﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="CreateDeploymentOperation.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace CloudBlitz.DeploymentManager.DeploymentOperations
{
    using System;
    using System.Globalization;
    using System.IO;

    using AzureManagement;
    using AzureManagement.AzureDataContracts;

    using CloudBlitz.DeploymentManager.DeploymentWorkflow;

    public class CreateDeploymentOperation : DeploymentOperationBase
    {
        private readonly IAzureServiceClientsFactory azureServiceClientsFactory;

        public CreateDeploymentOperation(IAzureServiceClientsFactory azureServiceClientsFactory) : base(10)
        {
            this.azureServiceClientsFactory = azureServiceClientsFactory;
        }

        protected override OperationResult ExecuteOverride(DeploymentContext context)
        {
            var azureServiceManagementClient = this.azureServiceClientsFactory.CreateServiceManagementClient(context.AzureCredentials);

            var label = string.Format("{0}{1}", context.ClusterDetails.Name, DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));
            var name = label.Replace("/", string.Empty).Replace(":", string.Empty).Replace(" ", string.Empty).ToLowerInvariant();

            name = name.Length > 63 ? name.Substring(0, 63) : name;

            try
            {
                this.RaiseProgressChangedEvent(0, string.Format("Creating new production deployment for hosted service \"{0}\"", context.HostedServiceName));

                var operationId = azureServiceManagementClient.CreateDeployment(
                                                                        context.HostedServiceName,
                                                                        DeploymentSlots.Production,
                                                                        new DeploymentDetails
                                                                        {
                                                                            Name = name,
                                                                            Label = label,
                                                                            Configuration = File.ReadAllText(context.ClusterDetails.ServiceConfigurationFilePath),
                                                                            PackageUrl = context.ClusterPackageDetails.CspkgFile,
                                                                            StartDeployment = true,
                                                                            TreatWarningsAsError = false
                                                                        }).Result;

                this.RaiseProgressChangedEvent(50, string.Format("Production deployment for hosted service \"{0}\" is being created, waiting for the operation to complete", context.HostedServiceName));

                var operation = azureServiceManagementClient.WaitOperationForCompletion(operationId, TimeSpan.MaxValue);

                if (operation.Status == OperationStatuses.Failed)
                {
                    return new OperationResult(DeploymentOperationStatus.Failed, operation.Error.Message);
                }

                this.RaiseProgressChangedEvent(100, string.Format("Production deployment for hosted service \"{0}\" has been created", context.HostedServiceName));
                return OperationResult.Success;
            }
            catch (Exception e)
            {
                return ExceptionHelper.HandleException(e);
            }
        }

        public void Rollback(DeploymentContext context)
        {
            var azureServiceManagementClient = this.azureServiceClientsFactory.CreateServiceManagementClient(context.AzureCredentials);
            var operationId = azureServiceManagementClient.DeleteDeployment(context.HostedServiceName, DeploymentSlots.Production).Result;

            azureServiceManagementClient.WaitOperationForCompletion(operationId, TimeSpan.MaxValue);
        }
    }
}